import json
import urllib
import urllib2
import base64

BASE_URL = 'http://api.gowalla.com/'

class Pygowalla:
    username = ''
    password = ''
    api_key = ''
    action = ''
    _opener = None
    
    def __init__(self,username,password,api_key, action=''):
        self.username = username
        self.password = password
        self.api_key = api_key
        self.action = action
        self._opener = self._getopener()

    def __getattr__(self,k):
        if self.action == '':
            return Pygowalla(self.username, self.password, self.api_key, k)
        else:
            return Pygowalla(self.username, self.password, self.api_key, self.action+'/'+k)

    def __call__(self, **kwargs):
        action_segments = self.action.split('/')

        #if id exists stick it in the second location of the array
        uid = kwargs.pop('id',False)
        if uid:
            action_segments.insert(1,str(uid))

        url =  BASE_URL+ ('/').join(action_segments)

        if kwargs:
            url += '?' + urllib.urlencode(kwargs.items())

        response = self._getresponse(url)
        return response

    def _getopener(self):
        passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
        passman.add_password(None,BASE_URL,self.username,self.password)
        authhandler = urllib2.HTTPBasicAuthHandler(passman)
        return urllib2.build_opener(authhandler)

    def _buildrequest(self,url):
        request = urllib2.Request(url=url,data=None)
        request.add_header('Accept', 'application/json')
        request.add_header('Content-Type', 'application/json')
        request.add_header('-Gowalla-API-Key',self.api_key)
        return request

    def _getresponse(self,url):
        response = self._opener.open(self._buildrequest(url))
        json_response = response.read()
        return json.loads(json_response)

        
        
